<template>
  <view class="warpper">
    <view class="content">
      <view class="line-cell">
        <view class="line-cell__left">
          {{ $t("order.Sell-Currency") }}
        </view>
        <view
          class="line-cell__right"
          :class="{ disabled: isEdit }"
          @click="
            () => {
              SelectPopupShow = true;
            }
          "
        >
          <view class="line-cell__right__text">
            {{ currencyLabel }}
          </view>
          <view class="iconfont icon-jiantou-you line-cell__right__icon"></view>
        </view>
      </view>

      <view class="line-cell">
        <view class="line-cell__left">
          {{ $t("order.Sales-Quantity") }}
        </view>
        <view class="line-cell__right" :class="{ disabled: isEdit }">
          <u--input
            type="digit"
            :placeholder="$t('order.Please-Enter')"
            border="none"
            v-model="releaseTradeForm.totalStock"
            @blur="handleBlur(releaseTradeForm.totalStock)"
            inputAlign="right"
          ></u--input>
          <view class="line-cell__right__text">
            {{ currencyLabel }}
          </view>
        </view>
      </view>

      <view class="line-cell">
        <view class="line-cell__left">
          {{ $t("newDeal.country") }}
        </view>
        <view
          class="line-cell__right"
          @click="
            () => {
              SelectCountryShow = true;
            }
          "
          :class="{ disabled: isEdit }"
        >
          <view
            class="line-cell__right__text"
            :class="{ 'thin-text': !releaseTradeForm.recipientCountry }"
          >
            {{
              releaseTradeForm.recipientCountry
                ? $t("order." + releaseTradeForm.recipientCountry)
                : $t("order.Please-Choose")
            }}
          </view>

          <view class="iconfont icon-jiantou-you line-cell__right__icon"></view>
        </view>
      </view>
    </view>

    <view class="content padding-box">
      <view class="title">
        {{ $t("newDeal.offlineCollection") }}
      </view>
      <u--textarea
        :placeholder="$t('order.CashOut-tips1')"
        border="none"
        height="80rpx"
        v-model="receiptAccountValue"
      ></u--textarea>
    </view>

    <view class="content">
      <view class="line-cell" style="height: 100rpx">
        <view class="line-cell__left"> 选择接收人 </view>
        <view class="line-cell__right" @click="chooseAcceptPerson">
          <view
            class="line-cell__right__text"
            :class="{ 'thin-text': !applyUserId.userId }"
          >
            {{
              applyUserId.userId
                ? applyUserId.nickName
                : $t("order.Please-Choose")
            }}
          </view>

          <view class="iconfont icon-jiantou-you line-cell__right__icon"></view>
        </view>
      </view>
    </view>

    <view class="bottom-box">
      <view class="bottom-box__tips">
        <view class="">
          {{ $t("order.CashOut-tips2") }}
        </view>
        <view class="">
          {{ $t("order.CashOut-tips3") }}
        </view>
      </view>
      <u-button
        class="bottom-box__btn"
        @click="nextHandle"
        :loading="isLoading"
        :loadingText="$t('newDeal.confirm_sending')"
      >
        {{ $t("newDeal.confirm_sending") }}
      </u-button>
    </view>

    <!-- 选择货币弹窗 -->
    <SelectPopup
      :show.sync="SelectPopupShow"
      :option="currencyOption"
      :title="$t('order.currency')"
      :value="releaseTradeForm.sourceCurrency"
      @finish="onChangeCurrency"
      v-if="SelectPopupShow"
      labelSigned="currency"
      valueSigned="id"
    ></SelectPopup>
    <!-- 选择国家弹窗 -->
    <SelectPopup
      :show.sync="SelectCountryShow"
      :option="CountryOption"
      :title="$t('order.Country')"
      :value="releaseTradeForm.recipientCountry"
      @finish="onChangeCountry"
      v-if="SelectCountryShow"
    ></SelectPopup>
  </view>
</template>

<script>
import {
  releaseTradeOrder,
  getCurrencyList,
  releaseOderAddress,
  getOderAddress,
  editTradeOrder,
  setShelfStatus,
} from "@/services/bourse.js";
import SelectPopup from "@/components/SelectPopup.vue";
import { mapState } from "vuex";
import { getWalletList } from "@/services/user.js";
import { createExchangeOrder, countryQueryList } from "@/services/new_api";

export default {
  data() {
    return {
      tabType: "danren",
      receiptAccountValue: "",
      walletList: [],
      releaseTradeForm: {
        tradeScene: 1,
        tradeType: 0,
        tradeDescription: "OTC交易",
        sourceCurrency: 1,
        totalStock: "",
        tradeAddressId: "",
        shelfStatus: 1, //	上架状态
        recipientCountry: "",
        exchangeDetailList: [
          {
            targetCurrencyId: 1,
            targetPrice: 1,
          },
        ],
      },
      currencyOption: [],
      SelectPopupShow: false,
      SelectCountryShow: false,
      isEdit: 0,
      isLoading: false,

      // submitData: {
      //   tradeDetai1Id: "",
      //   tradeId: "",
      //   applyUserId: "",
      //   targetCurrencyId: "",
      //   targetPrice: "",
      //   recipientCountry: "",
      //   shelfStatus: "1",
      //   totalStock: "",
      //   sourceCurrencyId: "",
      //   tradeDescription: "",
      //   tradeScene: "1",
      //   tradeType: "0",
      //   content: "",
      // },
      tradeDetai1Id: null,
      tradeId: null,
      applyUserId: {
        userId: "",
        nickName: "",
      },
    };
  },

  computed: {
    ...mapState(["currentOrderInfo"]),
    currencyLabel() {
      const arr = this.currencyOption?.filter(
        (t) => t.id == this.releaseTradeForm.sourceCurrency
      );
      if (arr.length > 0) {
        return arr[0].currency;
      } else {
        return "";
      }
    },
    ...mapState(["countryList"]),
    CountryOption() {
      const local = uni.getLocale();
      const obj = {
        "zh-Hans": "cn",
        ru: "ru",
        en: "en",
      };
      return this.countryList.map((item) => {
        return {
          label: item[obj[local]],
          value: item.en,
        };
      });
    },

    // CountryOption() {
    //   return [
    //     {
    //       label: this.$t("order.China"),
    //       value: "China",
    //     },
    //     {
    //       label: this.$t("order.Russia"),
    //       value: "Russia",
    //     },
    //   ];
    // },
  },
  components: {
    SelectPopup,
  },
  onLoad(option) {
    // console.log()
    if (option.fromData) {
      const res = JSON.parse(option.fromData);
      this.tradeDetai1Id = res.tradeDetai1Id;
      this.tradeId = res.tradeId;
    }
    this.getWalletListData();

    this.onMssage();
  },
  beforeDestroy() {
    console.log(999);
    uni.$off("sendUserId");
  },
  methods: {
    // 接收自定义事件 列表用户id
    onMssage() {
      uni.$on("sendUserId", (e) => {
        this.applyUserId = e;
      });
    },

    // 点击选择接收人
    chooseAcceptPerson() {
      uni.navigateTo({ url: "/pagesUser/select_recipient/select_recipient" });
    },

    handleSwitchTab(index) {
      this.tabIndex = index;
    },
    async getWalletListData() {
      var { result } = await getWalletList();
      this.walletList = result.rows;
      this.currencyOption = [...result.rows];
      this.currencyOption = this.currencyOption.filter((i) => {
        return i.currencyVo.isOpen == 1 && i.currencyVo.tradeOpen == 1;
      });
      this.currencyOption = this.currencyOption.map((it) => {
        return {
          ...it,
          currency: it.currencyVo.currency,
          id: it.currencyVo.id,
        };
      });
      console.log("this.currencyOption", this.currencyOption);
    },
    handleBlur(val) {
      try {
        // 限制小数点后四位
        if (val.includes(".")) {
          //小数点后的位数
          let numAfterDot = val.toString().split(".")[1].length;
          //小数点前的位数
          let numBeforeDot = val.toString().split(".")[0].length;
          //最大长度等于小数点前的位数+3（小数点加小数点后两位）
          this.maxlength = numBeforeDot + 5;
          //小数点后的位数大于2，截取
          if (numAfterDot > 4) {
            this.releaseTradeForm.totalStock = val.substr(0, numBeforeDot + 5);
          }
        }
      } catch (e) {
        //TODO handle the exception
      }

      if (val > this.filterList(this.releaseTradeForm.sourceCurrency)) {
        this.releaseTradeForm.totalStock = this.filterList(
          this.releaseTradeForm.sourceCurrency
        );

        return;
      }
    },
    filterList(val) {
      var data = this.walletList.filter(
        (t) => t.currencyVo?.isOpen == 1 && t.currencyId == val
      );

      return parseFloat(data[0]?.amount);
    },
    // 选择货币回调
    onChangeCurrency(val) {
      console.log(val);
      this.releaseTradeForm.exchangeDetailList[0].targetCurrencyId = val;
      this.releaseTradeForm.sourceCurrency = val;
    },
    // 选择国家回调
    onChangeCountry(val) {
      this.releaseTradeForm.recipientCountry = val;
    },
    // 点击发布回调
    async nextHandle() {
      const { success, msg } = this.verifyForm();
      if (!success) {
        uni.showToast({
          title: msg,
          duration: 2000,
          icon: "none",
        });
        return;
      }
      const obj = {
        tradeDetai1Id: this.tradeDetai1Id,
        tradeId: this.tradeDetai1Id,
        applyUserId: this.applyUserId.userId,
        targetCurrencyId:
          this.releaseTradeForm.exchangeDetailList[0].targetCurrencyId + "",
        targetPrice:
          this.releaseTradeForm.exchangeDetailList[0].targetPrice + "",
        recipientCountry: this.releaseTradeForm.recipientCountry,
        shelfStatus: "1",
        totalStock: this.releaseTradeForm.totalStock,
        sourceCurrencyId: this.releaseTradeForm.sourceCurrency + "",
        tradeDescription: this.releaseTradeForm.tradeDescription,
        tradeScene: this.releaseTradeForm.tradeScene,
        tradeType: this.releaseTradeForm.tradeType,
        content: this.receiptAccountValue,
      };
      console.log(obj);
      this.isLoading = true;
      try {
        const res = await createExchangeOrder(obj);
        console.log(res);
        this.isLoading = false;
      } catch (err) {
        this.isLoading = false;
      }
      return;
      // const { success, msg } = this.verifyForm();
      // if (success) {
      //   this.isLoading = true;
      //   const res = await releaseOderAddress({
      //     content: this.receiptAccountValue,
      //   });
      //   if (res.success) {
      //     // 编辑模式
      //     if (this.isEdit) {
      //       const obj = {
      //         tradeId: this.releaseTradeForm.tradeId,
      //         tradeAddressId: res.result.data,
      //         shelfStatus: 1,
      //       };
      //       this.releaseTradeForm.tradeAddressId = res.result.data;
      //       const resq = await editTradeOrder(obj);
      //       if (resq.success) {
      //         uni.showToast({
      //           title: this.$t("order.edited-successfully"),
      //           duration: 2000,
      //           icon: "none",
      //         });
      //         uni.navigateBack();
      //       }
      //     } else {
      //       this.releaseTradeForm.tradeAddressId = res.result.data;
      //       const resq = await releaseTradeOrder(this.releaseTradeForm);
      //       if (resq.success) {
      //         uni.showToast({
      //           title: this.$t("order.Published-successfully"),
      //           duration: 2000,
      //           icon: "none",
      //         });
      //         uni.navigateBack({
      //           delta: 2,
      //         });
      //       }
      //     }
      //   }
      //   this.isLoading = false;
      // } else {
      //   uni.showToast({
      //     title: msg,
      //     duration: 2000,
      //     icon: "none",
      //   });
      // }
    },
    // 验证表单
    verifyForm() {
      let res = {
        success: true,
        msg: "",
      };
      if (
        this.releaseTradeForm.totalStock == "" ||
        this.releaseTradeForm.totalStock == 0
      ) {
        res.success = false;
        res.msg = this.$t("order.verify-tips1");
        return res;
      }

      if (this.releaseTradeForm.recipientCountry == "") {
        res.success = false;
        res.msg = this.$t("order.verify-tips2");
        return res;
      }
      this.receiptAccountValue = this.receiptAccountValue.trim();
      if (this.receiptAccountValue == "") {
        res.success = false;
        res.msg = this.$t("order.verify-tips3");
        return res;
      }

      return res;
    },
  },
};
</script>

<style lang="scss" scoped>
.disabled {
  pointer-events: none !important;
  opacity: 0.4;
}

.warpper {
  .content {
    margin: 30rpx;
    border-radius: 20rpx;
    overflow: hidden;
    padding: 0 20rpx;
    background: #ffffff;

    & > view:last-child {
      box-shadow: none;
    }

    .line-cell {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 112rpx;
      background: #ffffff;
      box-shadow: inset 0px -2rpx 0px 0px rgba(0, 0, 0, 0.05);
      font-size: 28rpx;
      font-family: HarmonyOS Sans-Regular, HarmonyOS Sans;
      font-weight: 400;
      color: #000000;

      &__right {
        max-width: 320rpx;
        display: flex;
        align-items: center;

        &__text {
          margin-left: 10rpx;
        }

        .thin-text {
          color: rgba(0, 0, 0, 0.3);
        }

        .deep-text {
          color: #fe6600;
        }

        &__icon {
          font-size: 30rpx;
          color: rgba(0, 0, 0, 0.2);
          margin-left: 6rpx;
        }
      }
    }
  }

  .padding-box {
    padding: 36rpx 20rpx;

    .title {
      margin-bottom: 30rpx;
    }

    /deep/.u-textarea {
      padding: 0;
      min-height: 80rpx;
    }
  }

  .bottom-box {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 750rpx;
    background-color: #ffffff;

    &__tips {
      font-size: 28rpx;
      font-family: HarmonyOS Sans-Regular, HarmonyOS Sans;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.3);
      line-height: 40rpx;
      padding: 10rpx 30rpx;
      background-color: #f6f6f6;
    }

    &__btn {
      margin: 10rpx 30rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 690rpx;
      height: 80rpx;
      color: #ffffff;
      background: #61bdb2;
      border-radius: 80rpx;
    }
  }
}
</style>
